﻿using Newtonsoft.Json;
using RXY_Mall.Api.Common;
using RXY_Mall.Api.Models;
using RXY_Mall.Core;
using Senparc.Weixin.MP.Helpers;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi.OutputCache.V2;

namespace RXY_Mall.Api.Controllers
{
    /// <summary>
    /// 微信接口
    /// </summary>
    [RoutePrefix("Weixin")]
    [ApiSecurityFilter]
    public class WeixinController : BaseApiController
    {
        /// <summary>
        /// 微信配置信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetConfigure")]
        public async Task<Response<GetWeixinConfigureInfoOutput>> GetConfigure(string url)
        {
            Response<GetWeixinConfigureInfoOutput> result = new Response<GetWeixinConfigureInfoOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                var token = await GetToken(0);
                if (token.code != 1)
                {
                    result.msg = token.msg;
                    return result;
                }
                var ticket = await GetTicket(token.data.access_token);
                if (ticket.code != 1)
                {
                    result.msg = ticket.msg;
                    return result;
                }
                var timestamp = JSSDKHelper.GetTimestamp();
                var nonceStr = JSSDKHelper.GetNoncestr();
                var signature = JSSDKHelper.GetSignature(ticket.data.ticket, nonceStr, timestamp, url);

                GetWeixinConfigureInfoOutput output = new GetWeixinConfigureInfoOutput()
                {
                    timestamp = timestamp,
                    appId = "wx034f1b258856705b",
                    nonceStr = nonceStr,
                    signature = signature,
                };

                LogHelper.WriteLog(string.Format("timestamp:{0} nonceStr:{1} url:{2} signature:{3}", timestamp, nonceStr, url, signature));

                result.data = output;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetToken")]
        [CacheOutput(ClientTimeSpan = 7200, ServerTimeSpan = 7200)]
        public async Task<Response<GetToken>> GetToken(int id = 0)
        {
            Response<GetToken> result = new Response<GetToken>();
            result.code = 0;
            result.msg = "";

            try
            {
                string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", "wx034f1b258856705b", "84a8437eda1f7d7ea3418438e7390e75");
                using (var client = new HttpClient())
                {
                    // 创建一个异步GET请求，当请求返回时继续处理（Continue-With模式）
                    HttpResponseMessage response = await client.GetAsync(url);
                    string resultStr = await response.Content.ReadAsStringAsync();
                    result.data = JsonConvert.DeserializeObject<GetToken>(resultStr);
                    LogHelper.WriteLog(resultStr);
                    if (!string.IsNullOrEmpty(result.data.access_token) && result.data.access_token != "null")
                    {
                        result.code = 1;
                    }
                    else
                    {
                        result.msg = result.data.errmsg;
                    }
                    return result;
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得GetTicket
        /// </summary>
        /// <param name="access_token"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTicket")]
        [CacheOutput(ClientTimeSpan = 7200, ServerTimeSpan = 7200)]
        public async Task<Response<GetTicketOutput>> GetTicket(string access_token)
        {
            Response<GetTicketOutput> result = new Response<GetTicketOutput>();
            result.code = 0;
            result.msg = "";

            try
            {
                string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token);
                using (var client = new HttpClient())
                {
                    // 创建一个异步GET请求，当请求返回时继续处理（Continue-With模式）
                    HttpResponseMessage response = await client.GetAsync(url);
                    string resultStr = await response.Content.ReadAsStringAsync();

                    result.data = JsonConvert.DeserializeObject<GetTicketOutput>(resultStr);
                    if (resultStr.Contains("\"errmsg\":\"ok\""))
                    {
                        result.code = 1;
                        return result;
                    }
                    else
                    {
                        result.msg = result.data.errmsg;
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }
    }
}
